using System.Collections.Generic;
using System.Diagnostics;

namespace BizTalk.BuildGenerator
{
    /// <summary>
    /// Implements IComparer to sort a list of ApplicationResource objects based on their dependancy order
    /// </summary>
    public class ApplicationResourceComparer : IComparer<ApplicationResource>
    {
        #region IComparer<ApplicationResource> Members

        /// <summary>
        /// Compares application resources
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public int Compare(ApplicationResource x, ApplicationResource y)
        {           
            Trace.WriteLine(string.Format("Checking dependancy between {0} and {1}", x.FullName, y.FullName));

            bool myReference = DependsOn(x, y);
            if (myReference)
                return 1;

            bool yourReference = DependsOn(y, x);
            if (yourReference)
                return -1;

            return 0;
        }

        #endregion

        /// <summary>
        /// Recurses through the dependancies to find if one appembly depends on another in its reference tree
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        private static bool DependsOn(ApplicationResource x, ApplicationResource y)
        {            
            foreach (ApplicationResource dependant in x.DependantResources)
            {
                if (dependant == y)
                    return true;               

                return DependsOn(dependant, y);
            }

            return false;
        }
    }
}